import json
import re

from django.core.paginator import PageNotAnInteger, Paginator
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from django.template.loader import render_to_string
from django.http import HttpResponseNotFound, HttpResponseServerError, HttpResponseForbidden, HttpResponseBadRequest
from pypinyin import pinyin

# Create your views here.
from Oa_system.models import Staffing
from personal_center.models import User, Function


def page_not_found(request, *args, **kwargs):
    return HttpResponseNotFound(render_to_string('project_error/404.html', request=request))


def server_error(request, *args, **kwargs):
    return HttpResponseServerError(render_to_string('500.html', request=request))


class my_draft(View):
    def get(self, request):
        return render(request, 'my-draft.html')


class StaffingList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': position, 'department': department}
        return render(request, 'system_setup/create_staffing.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = Staffing.objects.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'user': ", ".join([i.real_name for i in obj.post_personnel.all()]),
                      'station': obj.station}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class StaffingDeleteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Staffing.objects.get(id=id)

        obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class StaffingView(View):
    def post(self, request):
        user = request.POST.get('user', None)
        station = request.POST.get('station', None)

        user_list = re.findall('\((.*?)\)', user)
        user_obj = User.objects.filter(job_number__in=user_list)
        print(user_obj, station)
        staff_obj = Staffing.objects.create(user=request.user, station=station)
        for i in user_obj:
            staff_obj.post_personnel.add(i)
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FunctionListView(View):
    def get(self, request):
        # 返回创建页面
        search_value = request.GET.get("search_value", None)
        objs = Function.objects.all().order_by('-create_time')
        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'system_setup/function_list.html', context)

    def post(self, request):
        describe = request.POST.get('describe', None)
        people = request.POST.get('people', None)
        group_id = request.POST.get('id', None)
        peoples = re.findall('\((.*?)\)', people)
        if group_id:
            function_obj = Function.objects.get(id=group_id)
            # 删除现有小组人员
            for user_obj in function_obj.function_ids_users.all():
                user_obj.function_ids.remove(function_obj)

            for user_obj in User.objects.filter(job_number__in=list(set(peoples))).all():
                user_obj.function_ids.add(function_obj)
            returnData = {'code': 200, 'message': '添加成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        packet = "".join([i[0][0] for i in pinyin(describe)]).upper()
        function_obj = Function.objects.create(packet=packet,describe=describe)
        for user_obj in User.objects.filter(job_number__in=peoples).all():
            user_obj.function_ids.add(function_obj)
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FunctionDeleteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Function.objects.get(id=id)
        for user_obj in obj.function_ids_users.all():
            user_obj.function_ids.remove(obj)
        obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

